package com.example.preparedstatement.crud;

import com.example.statement.User;
import com.example.util.JDBCUtils;
import org.junit.Test;

import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.Scanner;

// 演示PreparedStatement解决SQL注入问题
public class PreparedStatementTest {

    // 通用查询单条记录
    public static <T> T getInstance(Class<T> clazz, String sql, Object... args) {
        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;
        try {
            // 获取连接
            connection = JDBCUtils.getConnection();

            // 编译SQL
            preparedStatement = connection.prepareStatement(sql);
            // 设置参数
            for (int i = 0; i < args.length; i++) {
                preparedStatement.setObject(i + 1, args[i]);
            }

            // 查询结果
            resultSet = preparedStatement.executeQuery();
            // 获取结果集元数据
            ResultSetMetaData resultSetMetaData = resultSet.getMetaData();
            int columnCount = resultSetMetaData.getColumnCount();

            // 遍历结果集
            if (resultSet.next()) {
                T t = clazz.newInstance();
                for (int i = 0; i < columnCount; i++) {
                    Object columnValue = resultSet.getObject(i + 1);
                    // 获取列名
                    String columnName = resultSetMetaData.getColumnLabel(i + 1);

                    // 通过反射设置属性值
                    Field field = clazz.getDeclaredField(columnName);
                    field.setAccessible(true);
                    field.set(t, columnValue);
                }
                return t;
            }
        } catch (Exception exception) {
            exception.printStackTrace();
        } finally {
            // 释放资源
            JDBCUtils.closeResource(connection, preparedStatement, resultSet);
        }
        return null;
    }

    @Test
    public void testLogin() {
        Scanner scanner = new Scanner(System.in);
        System.out.print("用户名：");
        String userName = scanner.nextLine();
        System.out.print("密 码：");
        String password = scanner.nextLine();

        // 模拟如下输入不会再出现SQL注入：
        // 用户名：1' or
        // 密码：=1 or '1' and '1
        String sql = "SELECT user, password FROM user_table WHERE user = ? AND password = ?";
        User user = getInstance(User.class, sql, userName, password);
        if (user != null) {
            System.out.println("登录成功！");
        } else {
            System.out.println("登录失败！");
        }
    }

}
